package com.parkingspace.config;

import com.parkingspace.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * ClassName: AuthFilter
 * Package: com.gzp.config
 *
 * @author: guanzepeng
 * @Date: 2021/4/25 22:56 星期日
 * @Description:
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

		// 首先判断请求的是不是登录，如果是，则直接放行，不用检查token了！
		String path = exchange.getRequest().getURI().getPath();
		String[] split = path.split("/");
		for (String s : split) {
			if ("login".equals(s) || "registered".equals(s)) {
				// 放行
				System.out.println(s+"请求进行放行!");
				return chain.filter(exchange);
			}
		}
//		if ("/e-user/user/login".equals(path)) {
//			// 放行
//			log.info("{}请求进行放行!",split[i]);
//			return chain.filter(exchange);
//		}
		log.info("header:{}",exchange.getRequest().getHeaders());
		String token = exchange.getRequest().getHeaders().getFirst("satoken");
		if (StringUtils.isEmpty(token)) {
			System.out.println(("没有Token!"));
			// 流程走到这里，说明客户端的请求中没有携带令牌，那么就要响应401错误
			exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
			return exchange.getResponse().setComplete();
		}

		// 流程能走到这里，说明请求中携带token了！那么要对这个token进行校验
		boolean b = JwtUtils.verifyToken(token);
		if (!b) {
			System.out.println("有token，但是没有通过校验");
			// 校验没有通过
			exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
			return exchange.getResponse().setComplete();
		}

		System.out.println("token校验通过");
		// 放行
		return chain.filter(exchange);
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
